<!-- PlayOne.vue -->
<template>
  <div class="play-section">
    <h2 class="play-title">
      <span>{{ title }}</span>
        <div>
            <el-button type="primary" @click="saveAs" :loading="loading">保存</el-button>
            <el-button type="primary" @click="lastTimeNo" style="margin-left: 10px;" >上一张</el-button>
            <el-button type="primary" @click="resetData" style="margin-left: 10px;" >重置</el-button>
        </div>
    </h2>

    <div>
      <el-input placeholder="请输入名称" class="input-with-select" style="width: 70%; margin: 3px 0 10px 0" v-model="form.buyName">
        <el-button slot="prepend">用户名称</el-button>
      </el-input>

       <el-select v-model="form.sheng" @change="shengCHange"  style="width: 28%; margin: 3px 0 10px 1.5%" placeholder="请选择">
            <el-option
                v-for="item in dictList"
                :key="item.dictValue"
                :label="item.dictLabel"
                :value="item.dictValue">
            </el-option>
        </el-select>
    </div>
   <div>
    <el-card class="box-card"
        v-for="(item,index) in form.itemListView"
        :key="index"
    >
        <el-input placeholder="单号1" class="input-with-select ipt-style" min="0" max="9"  type="number"  @input="validateMultiple(item,index,'one')"  v-model="item.one">

        </el-input>
        <el-input placeholder="单号2" class="input-with-select  ipt-style" min="0"  max="9" type="number" v-model="item.two"  @input="validateMultiple(item,index,'two')" ></el-input>
        <el-input placeholder="单号3" class="input-with-select ipt-style" style="margin-right: 0;" min="0"  max="9"  type="number" v-model="item.three"  @input="validateMultiple(item,index,'three')"></el-input>
        <!-- 单/组 -->
        <div :class="item.itemType=='单'?'dan':'zu'" @click="itemChangetemType(item,index)">{{item.itemType}}</div>
        <el-input placeholder="倍数" class="input-with-select ipt-style" min="0"  type="number" v-model="item.itemMult"></el-input>
    </el-card>

   </div>



    <CustomDialog @close="form = {}" ref="CustomDialog"></CustomDialog>
  </div>
</template>

<script>
import { saveAs } from "file-saver";
import { saveLotteryVo2 ,dataDictType,getLastLotter} from "@/api/bussiness";
import CustomDialog from "../modules/CustomDialog.vue";
import axios from 'axios'
export default {
  name: "PlayOne",
  components: {
    CustomDialog,
  },
  props: {
    // 接收父组件传入的初始值
    noArrStr: {
      type: String,
      default: "",
    },
    title: {
      type: String,
      default: "",
    },
    lotteryType: {
      type: String,
      default: "",
    },

    lotteryNo: {
      type: String,
      default: "",
    },
    dictList: {
      type: Array,
      default:[],
    },
  },
  data() {
    return {
        loading: false,
      options: [],
      form: {
        baseBuyNo: "",
        lotteryNo: "",
        groupValue: "",
        buyGroup: 0, //购买组
        multiple: 0, //购买直
        buyName: "", //用户名称
        sheng:'',  //省
        itemListView: [
            {
                one: '',
                two: '',
                three: '',
                itemType: '单',
                itemMult: 1,
                itemVal:'',
            },
            {
                one: '',
                two: '',
                three: '',
                itemType: '单',
                itemMult: 1,
                itemVal:'',
            },
            {
                one: '',
                two: '',
                three: '',
                itemType: '单',
                itemMult: 1,
                itemVal:'',
            },
            {
                one: '',
                two: '',
                three: '',
                itemType: '单',
                itemMult: 1,
                itemVal:'',
            },
            {
                one: '',
                two: '',
                three: '',
                itemType: '单',
                itemMult: 1,
                itemVal:'',
            },
        ]
      },
    };
  },
  watch: {
    // 监听父组件传入的值变化
    noArrStr(val) {
      this.form.baseBuyNo = val;
      },
     dictList: {
        handler(newVal) {
            this.initShengFromLocalStorage();
        },
        immediate: true // 立即执行一次，组件创建时也会执行
    }
    },
   mounted() {
       // 页面初始化时从localStorage取出存储的省值
    this.$nextTick(() => {
      this.initShengFromLocalStorage();
    });


  },
    methods: {
        validateMultiple (value, index, type) {
            // 确保输入值不小于0
            if (this.form.itemListView[index][type] < 0) {
                this.form.itemListView[index][type] = 0;
            }
            if (this.form.itemListView[index][type] > 9)
            {
                this.form.itemListView[index][type] = 9;
            }
            if (this.form.itemListView[index][type].length == 2)
            {
              let tm = this.form.itemListView[index][type];
              this.form.itemListView[index][type] = Number(tm)
            }
        },
        itemChangetemType (item, index) {
        // 切换 itemType: 单 -> 组, 组 -> 单
        var newItemType = ""
        if (item.itemType === '组')
        {
            newItemType = "单"
        }
        if (item.itemType === '单')
        {
            newItemType = "组"
        }
        this.form.itemListView[index].itemType = newItemType;
        },
        resetData () {

            this.form= {
                baseBuyNo: "",
                lotteryNo: "",
                groupValue: "",
                buyGroup: 0, //购买组
                multiple: 0, //购买直
                buyName: "", //用户名称
                sheng:'',  //省
                itemListView: [
                    {
                        one: '',
                        two: '',
                        three: '',
                        itemType: '单',
                        itemMult: 1,
                        itemVal:'',
                    },
                    {
                        one: '',
                        two: '',
                        three: '',
                        itemType: '单',
                        itemMult: 1,
                        itemVal:'',
                    },
                    {
                        one: '',
                        two: '',
                        three: '',
                        itemType: '单',
                        itemMult: 1,
                        itemVal:'',
                    },
                    {
                        one: '',
                        two: '',
                        three: '',
                        itemType: '单',
                        itemMult: 1,
                        itemVal:'',
                    },
                    {
                        one: '',
                        two: '',
                        three: '',
                        itemType: '单',
                        itemMult: 1,
                        itemVal:'',
                    },
                ]
            }
            this.initShengFromLocalStorage();
        },
        async lastTimeNo () {
           const lastNo = await getLastLotter();
            if (lastNo.code==200) {
                const { buyName, sheng, itemList } = lastNo.data;
                const itemListNew = []
                if (itemList.length>0)
                {
                    itemList.forEach(item => {
                        const result = item.itemVal.split('').map(Number);
                        itemListNew.push({
                            one: result[0],
                            two: result[1],
                            three: result[2],
                            itemType: item.itemType,
                            itemMult: item.itemMult,
                        })
                    });

                }

                if (itemListNew.length<5)
                {
                    const numbers = 5-itemListNew.length;
                    for (let i = 0; i < numbers; i++) {
                        itemListNew.push({
                            one: '',
                            two: '',
                            three: '',
                            itemType: '单',
                            itemMult: 1,
                            itemVal:'',
                        })
                    }

                }


                this.form = {
                    buyName: buyName,
                    sheng: sheng,
                    itemListView: itemListNew,
                };
            }
        },
        shengCHange (val) {
            if (val) {
              localStorage.setItem('selectedSheng', val);
            }
        },
        initShengFromLocalStorage() {
          try {
              const savedSheng = localStorage.getItem('selectedSheng');
                //console.log("缓存种的身份")
              //console.log(savedSheng)
              //console.log(this.dictList);
                if (savedSheng) {
                this.form.sheng = savedSheng;
                } else if (this.dictList && this.dictList.length > 0) {
                // 如果本地存储中没有值，则默认选中第一个
                    this.form.sheng = this.dictList[0].dictValue;
                        this.$forceUpdate()

                }
            } catch (error) {
                console.error('从localStorage读取省值时出错:', error);
            }
        },
    async saveAs() {
      this.loading = true;

      if (!this.form.buyName) {
          this.$message.error("请输入" + this.title + "名称！");
          this.loading = false;
        return;
      }
        this.form.lotteryType = this.lotteryType;
        this.form.itemList = []
        this.form.itemListView.forEach(item => {
          var itemVal = String(item.one) + String(item.two) + String(item.three);
          item.itemVal = itemVal
            /* if (item.one && item.two && item.three && item.itemMult)
            {
            var itemVal = String(item.one) + String(item.two) + String(item.three);
                item.itemVal = itemVal
                this.form.itemList.push({
                    itemVal: itemVal,
                    itemMult: item.itemMult,
                    itemType: item.itemType,
                })
            } */
            if(itemVal && itemVal.length == 3){
              this.form.itemList.push({
                  itemVal: itemVal,
                  itemMult: item.itemMult,
                  itemType: item.itemType,
              })
            }
        });
        this.loading = false;

      saveLotteryVo2(this.form).then(res => {
        if (res.code == 200) {
        this.thisFromRest()
        const pdfContent = res.data.body;
        const fileName = this.getFileNameFromHeaders(res.data.headers);

        // 将Base64转换为Blob
        const byteCharacters = atob(pdfContent);
        const byteNumbers = new Array(byteCharacters.length);
        for (let i = 0; i < byteCharacters.length; i++) {
          byteNumbers[i] = byteCharacters.charCodeAt(i);
        }
        const byteArray = new Uint8Array(byteNumbers);
        const blob = new Blob([byteArray], { type: 'application/pdf' });

        // 创建URL并打开
        const blobUrl = URL.createObjectURL(blob);
        window.open(blobUrl, '_blank');

        // 清理URL对象
        setTimeout(() => URL.revokeObjectURL(blobUrl), 100);

          //console.log(res)
          this.$message.success("保存成功！");
          /* this.$refs.CustomDialog.open(this.form);
            this.form = {
                buyGroup:0,
                multiple:0,
            };

            this.$emit('close') */
          this.loading = false;
        } else {
          console.log("我保存失败了");
          this.$message.error("保存失败！");
           this.form = {
              buyGroup:0,
              multiple:0,
          };
          this.$emit('close')
          this.loading = false;
        }
      });
      this.loading = false;
      //console.log(this.form);
        },

        thisFromRest () {
            this.form = {
                baseBuyNo: "",
                lotteryNo: "",
                groupValue: "",
                buyGroup: 0, //购买组
                multiple: 0, //购买直
                buyName: "", //用户名称
                sheng:'',  //省
                itemListView: [
                    {
                        one: '',
                        two: '',
                        three: '',
                        itemType: '单',
                        itemMult: 1,
                        itemVal:'',
                    },
                    {
                        one: '',
                        two: '',
                        three: '',
                        itemType: '单',
                        itemMult: 1,
                        itemVal:'',
                    },
                    {
                        one: '',
                        two: '',
                        three: '',
                        itemType: '单',
                        itemMult: 1,
                        itemVal:'',
                    },
                    {
                        one: '',
                        two: '',
                        three: '',
                        itemType: '单',
                        itemMult: 1,
                        itemVal:'',
                    },
                    {
                        one: '',
                        two: '',
                        three: '',
                        itemType: '单',
                        itemMult: 1,
                        itemVal:'',
                    },
                ]
            }
             this.initShengFromLocalStorage();
        },
  getFileNameFromHeaders(headers) {
      const contentDisposition = headers['Content-Disposition'][0];
      const match = contentDisposition.match(/filename="(.+)"/);
      return match ? match[1] : 'document.pdf';
    },
    chunkString(str, size) {
      const chunks = [];
      for (let i = 0; i < str.length; i += size) {
        chunks.push(str.slice(i, i + size));
      }
      const reBack = chunks.filter(chunk => chunk.length === size);
      return reBack.length > 0 ? reBack.join(",") : "";
    },
  },
};
</script>

<style scoped lang='scss'>
::v-deep {
    .el-card__body{
        padding: 4px 20px 5px 20px;
    }
}
.ipt-style{
    width: 18%; margin-right: 20px
}
.dan{
    display: inline-block;
    height: 36px;
    line-height: 36px;
    width: 36px;
    cursor: pointer;
    text-align: center;
    color: rgb(255, 255, 255);
    background-color: rgb(245, 108, 108);
    border-color: rgb(245, 108, 108);
    border-radius: 3px;
    margin: 0 10px;
}
.zu{
    display: inline-block;
    height: 36px;
    line-height: 36px;
       cursor: pointer;
    width: 36px;
    text-align: center;
    color: rgb(255, 255, 255);
    background-color: rgb(103, 194, 58);
    border-color: rgb(103, 194, 58);
    border-radius: 3px;
    margin: 0 10px;
}

.box-card{
    margin-top: 1%;
}
.result-text {
  white-space: pre-wrap;
  word-wrap: break-word;
  overflow: auto;
  max-width: 100%;
  margin-top: 10px;
  padding: 5px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  background-color: #f9f9f9;
}
.play-section {
  margin-bottom: 30px;
  padding: 20px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  background-color: #fff;
}

.play-title {
  font-size: 18px;
  color: #409eff;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
  display: flex;
  justify-content: space-between;
  margin: 5px 0 10px 0;
  padding-bottom: 10px;
}

.dis-flex {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.font-red {
  color: rgb(226, 24, 24);
  font-weight: 700;
  margin: 0 5px;
  font-size: 19px;
}

.input-with-select ::v-deep .el-input-group__append {
  background-color: #409eff;
  color: white;
  border-color: #409eff;
}
</style>
